package com.young.controller;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.young.config.MyContainerListener;
import com.young.entity.Person;
import com.young.repository.AddressRepository;
import com.young.repository.PersonRepository;

@Controller
@RequestMapping("/person")
public class PersonController {

	@Autowired
	private AddressRepository addressRepository;
	
	@Autowired
	private PersonRepository personRepository;
	
	
	@GetMapping({"","/"})
	public String person(Map<String, Object> map){
		map.put("person", personRepository.findAll());
		return "index";
	}
	
	
	@PostMapping({"","/"})
	public String add(@Valid Person person, BindingResult bindingResult, Map<String, Object> map){
		if(bindingResult.hasErrors()){
			map.put("msg", bindingResult.getFieldError().getDefaultMessage());
			map.put("addrs", addressRepository.findAll());
			map.put("person", null);// 移除提交的person，否则表单页面判断未put请求
			return "person_add";
		}
		person.setRegisterDate(new Date());
		person.setAvatar("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=410935453,2828229054&fm=27&gp=0.jpg");
		personRepository.save(person);
		return "redirect:/person";
	}
	
	
	@DeleteMapping("/{id}")
	public String delete(@PathVariable long id){
		personRepository.delete(id);
		return "redirect:/person";
	}
	
	
	@GetMapping("/{id}")
	public String edit(@PathVariable long id, Map<String, Object> map){
		Person person = personRepository.findOne(id);
		if(null != person){
			map.put("addrs", addressRepository.findAll());
			map.put("person", person);
			return "person_add";
		}else{
			return "index";
		}
	}
	
	
	@PutMapping("/")
	public String update(@Valid Person person, BindingResult bindingResult, Map<String, Object> map){
		if(bindingResult.hasErrors()){
			map.put("msg", bindingResult.getFieldError().getDefaultMessage());
			map.put("addrs", addressRepository.findAll());
			return "person_add";
		}
		
		person.setRegisterDate(new Date());
		personRepository.save(person);
		return "redirect:/person";
	}
	
	@GetMapping("/add")
	public String add(Map<String, Object> map){
		map.put("addrs",addressRepository.findAll());
		return "person_add";
	}
	
	
	@GetMapping("/avatar/{id}")
	public String avatarChange(@PathVariable long id, Map<String, Object> map){
		Person person = personRepository.findOne(id);
		map.put("person", person);
		return "person_avatar";
	}
	
	
	@PostMapping("/avatar")
	public String avatar(long id, @RequestParam("avatar") MultipartFile file, HttpServletRequest request){
		
		try {
			String dir = request.getServletContext().getRealPath("static") + File.separator;
			File dirFile = new File(dir);
			if(!dirFile.exists()){
				dirFile.mkdirs();
			}

			file.transferTo(new File(dir + file.getOriginalFilename()));
			
			Person person = personRepository.findOne(id);
			
			person.setAvatar("http://" + InetAddress.getLocalHost().getHostAddress() + ":" + MyContainerListener.getPort() + 
					"/static/" + file.getOriginalFilename());
			personRepository.save(person);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "redirect:/person";
	}
}
